package com.itheima.web.controller;

import cn.hutool.Hutool;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
@CrossOrigin(value = "{http://127.0.0.1:81,http://127.0.0.1:82}")
@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserService userService;
    //接受手机号
    @GetMapping("/sendMsg")
    public String sendMsg(String telephone,HttpSession session){
    //生成六位随机数
        String smsCode = RandomUtil.randomNumbers(6);
        //将随机数通过短信发送给用户，并将随机数保存到session
        //此处省略发送
        System.out.println(smsCode);
        session.setAttribute("smsCode"+telephone,smsCode);
        //返回发送成功
        return "ok";
    }
    //登陆
    @PostMapping("/submit")
    public Map<String,Object> submit(@RequestBody Map<String,String> map,HttpSession session){
        //事先声明返回Map
        Map<String, Object> loginResult = new HashMap<>();
        //调用service查询数据库是否有此人
        System.out.println(map);
        String telephone = map.get("telephone");
        String msgCode = map.get("msgCode");
        String smsCode = (String) session.getAttribute("smsCode"+telephone);
        //判断验证码
        if (msgCode==null || smsCode==null || (!smsCode.equals(msgCode))){
            loginResult.put("msg",0);
            return loginResult;
        }
        User user = userService.findByTelePhone(telephone);
        if (user==null){
            loginResult.put("msg",0);
            return loginResult;
        }
        //登陆成功
        //清除敏感信息
        user.setPassword(null);
        //将用户信息转为map
        Map<String, Object> userMap = BeanUtil.beanToMap(user);
        //将该用户的map制作为令牌
        String token = JwtUtil.createToken(userMap);
        //发送给客户端验证正确的信息和token
        loginResult.put("msg",1);
        loginResult.put("token",token);
        return loginResult;
    }
    //进入main.html时验证是否有令牌
    @GetMapping("/verify")
    public String verify(@RequestHeader("Authorization") String token){
        //将客户端本地存储的令牌接受，再次进行加盐验证
        try {
            Map map = JwtUtil.parseToken(token);
            System.out.println(map);
        } catch (Exception e) {
            e.printStackTrace();
            return "401";
        }
        return "ok";
    }
}
